package org.example.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.scene.input.DataFormat;
import org.example.model.User;
import org.junit.Test;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

public class WebUtil {
 /*   private static final ObjectMapper M=new ObjectMapper();
   //把消息中的时间日期转化为 年-月-日 时：分：秒
    static {
        SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  M.setDateFormat(df);
   }*/
   //改成双重校验锁的单例模式
    private static ObjectMapper M=null;
    private static ObjectMapper getMapper(){
       if (M==null){
          synchronized (WebUtil.class){
              if (M==null){
                  M=new ObjectMapper();
                  SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  M.setDateFormat(df);
              }
           }
       }
       return M;
    }


    public static final String LOCAL_HEAD_PATH="E://TMP";

    //提供Java对象转化为json字符串的方法
    public static String write(Object o){
        try {
            return getMapper().writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw  new RuntimeException("转化Java对象为字符串出错",e);
        }
    }
    //json 转为java对象  两个方法InputStream String
    public static <T> T read (InputStream is,Class<T> clazz){
        try {
            return getMapper().readValue(is,clazz);
        } catch (IOException e) {
            throw new RuntimeException("替换输入流json字符串为JAVA出错",e);
        }
    }
    public static <T> T read (String is,Class<T> clazz){
        try {
            return getMapper().readValue(is,clazz);
        } catch (IOException e) {
            throw new RuntimeException("替换输入流json字符串为JAVA出错",e);
        }
    }

 public static User getLoginUser(HttpSession session){
        if (session!=null){
            //表示用户登录  可以获取session中用户的信息
            //获取登录名
            return (User) session.getAttribute("user");
        }
        return null;
 }




 @Test
public void TestWrite(){
        User u =new User();
        u.setId(2);
        u.setUsername("a");
        u.setPassword("123");
        u.setNickname("AAA");
        System.out.println(write(u));
 }
 @Test
 public void  readTest(){
     String s = "{\"id\":2,\"username\":\"张三\",\"password\":\"123\",\"nickname\":\"哈哈\",\"logoutTime\":null}";
         System.out.println(read(s,User.class));
    }

}
